//
//  LRLocationManager.m
//  本地生活圈
//
//  Created by admin on 15/8/11.
//  Copyright (c) 2015年 懒人. All rights reserved.
//

#import "LRLocationManager.h"


@interface LRLocationManager ()<CLLocationManagerDelegate>
/**
 *  manager
 */
@property (nonatomic, strong) CLLocationManager *manager;
/**
 *  代码块
 */
@property (nonatomic, copy) successBlock sBlock;
/**
 *
 */
@property (nonatomic, copy) failBlock fBloack;
/**
 *  是否定位成功
 */
@property (nonatomic, assign) BOOL isSuccess;
@end

@implementation LRLocationManager

#pragma mark - manager 懒加载
- (CLLocationManager *)manager
{
    if (!_manager)
    {
        _manager = [[CLLocationManager alloc]init];
        if ([_manager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [_manager requestAlwaysAuthorization];
        }
        _manager.delegate = self;
    }
    return _manager;  // 单利模式？
}

// 必须实例化
+ (LRLocationManager *)shareInstance{
    
    static LRLocationManager *man = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       man = [[LRLocationManager alloc]init];
        
    });
    return man;
    
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusNotDetermined)
    {
        // 定位失败
        self.fBloack([NSError errorWithDomain:@"定位失败" code:0 userInfo:nil]);
    }
    else
        [self.manager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 由于持续调用
    if (self.isSuccess) return;

    CLLocation *location = locations.lastObject;
    if (!location)
    {
        self.isSuccess = YES;
        self.sBlock(location);
        [self.manager stopUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    self.fBloack(error);
    [self.manager stopUpdatingLocation];
}

#pragma mark - 定位block回调
+ (void)getLocationSuccess:(successBlock)sBlock fail:(failBlock)fBlock
{
//    [[LRLocationManager new] getLocationSuccess:sBlock fail:fBlock]; // 空对象

    [[LRLocationManager shareInstance] getLocationSuccess:sBlock fail:fBlock];
}

- (void)getLocationSuccess:(successBlock)sBlock fail:(failBlock)fBlock
{
    self.sBlock = sBlock;
    self.fBloack = fBlock;
    
    [self.manager startUpdatingLocation];
}

@end
